<template>
	<view>
		<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :multiple="multiple"
			:maxCount="disabled?fileList.length: maxCount" :accept="accept" :deletable="!disabled"
			v-bind="attrs"></u-upload>
		<slot name="videos" :prop="fileList">
			<view v-if="accept==='video'">
				<view class="file-view" v-for="(item,index) in fileList" :key="index">
					<view style="flex: 1;">
						<up-text :lines="1" size="12" bold
							:text="item.fileName+item.fileSuffix||upState[item.status]"></up-text>
					</view>
					<view class="p-l-5 p-r-5" v-if="item.downloadUrl||item.status==='success'">
						<up-text size="12" bold type="primary" text="点击查看" @click="prevideo(item)"></up-text>
					</view>
				</view>
				<u-modal :show="modals" title="视频" confirmText="关闭" @confirm="modals=false">
					<view>
						<video :src="videoSrc"></video>
					</view>
				</u-modal>
			</view>
		</slot>
	</view>
</template>
<script setup>
	import {
		getAuthorization,
		getUserId
	} from '@/router/auth.js';

	const props = defineProps({
		modelValue: [Array, String],
		maxCount: {
			type: Number,
			default: 32,
		},
		multiple: {
			type: Boolean,
			default: true,
		},
		accept: {
			type: String,
			default: 'image',
		},
		disabled: {
			type: Boolean,
			default: false,
		}
	});
	let attrs = useAttrs()

	const modals = ref(false)
	const videoSrc = ref('')
	const fileList = ref([]);
	const upState = {
		uploading: '上传中',
		failed: '上传失败',
		success: '上传成功'
	}
	watch(
		() => props.modelValue,
		(val = []) => {
			if (!isEqual(val, fileList.value)) {
				const valData = Array.isArray(val) ? val : [val];

				fileList.value = valData?.map(item => ({
					id: item.id,
					downloadUrl: item.downloadUrl,
					src: item.downloadUrl,
					url: item.downloadUrl,
					fileName: item.fileName,
					fileSizeFormat: item.fileSizeFormat,
					fileSize: item.fileSize,
					fileSuffix: item.fileSuffix,
				}));
			}
		}, {
			immediate: true
		}
	);
	const emits = defineEmits(["update:modelValue"]);

	watch(
		fileList,
		val => {
			val.forEach(item => {
				if (item.message === '成功') emits("update:modelValue", val);
			})
		}, {
			deep: true
		}
	);

	// 关闭模态框
	function prevideo(e) {
		modals.value = true
		videoSrc.value = e.downloadUrl
	}

	// 删除图片
	const deletePic = event => {
		fileList.value.splice(event.index, 1);
		emits("update:modelValue", fileList.value)
	};

	// 新增图片
	const afterRead = async event => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList.value.length;
		lists.map(item => {
			fileList.value.push({
				...item,
				status: 'uploading',
				message: '上传中'
			});
		});
		for (let i = 0; i < lists.length; i++) {
			uploadFilePromise(lists[i].url).then(result => {
				const res = JSON.parse(result)
				if (res.code === 200) {
					fileList.value.splice(fileListLen, 1, {
						id: res.data.id,
						downloadUrl: '/equipmentcd/' + res.data.storageUrl,
						url: '/equipmentcd/' + res.data.storageUrl,
						fileName: res.data.fileName,
						fileSizeFormat: res.data.fileSizeFormat,
						fileSize: res.data.fileSize,
						fileSuffix: res.data.fileSuffix,
						status: 'success',
						message: '成功',
					});
					uni.showToast({
						icon: 'none',
						title: '上传成功'
					})
				} else {
					let item = fileList.value[fileListLen]
					fileList.value.splice(fileListLen, 1, {
						...item,
						status: 'failed',
						message: '失败'
					})
					uni.showToast({
						icon: 'none',
						title: '上传失败'
					})
				}
				fileListLen++
			});
		}
	};

	const uploadFilePromise = url => {
		return new Promise((resolve, reject) => {
			const header = {}
			const Authorization = getAuthorization()
			const UserId = getUserId()

			if (Authorization) header['Authorization'] = 'Bearer ' + Authorization;
			if (UserId) header['Gneecuserid'] = UserId;

			// #ifdef APP-PLUS
			const apiBaseURL = uni.getStorageSync('BaseUrl')
			// #endif

			// #ifdef WEB
			const apiBaseURL = '/prod-api'
			// #endif

			uni.uploadFile({
				url: apiBaseURL + "/rdfile/data/upload",
				filePath: url,
				name: "file",
				header,
				success: res => {
					setTimeout(() => {
						resolve(res.data);
					}, 500);
				},
				fail: err => {
					reject(err)
				}
			});
		});
	};
</script>

<style scoped lang="scss">
	.file-view {
		padding: 10rpx;
		height: 50rpx;
		margin-bottom: 10rpx;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		background-color: #e7efff;
	}
</style>